#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 1024
#define OPSZ 4

int calculate(int opnum, int ops[], char op);

int main(int argc, char *argv[])
{
    int serv_sock, clnt_sock;
    char opinfo[BUF_SIZE];
    int result, op_cnt;
    int recv_cnt, recv_len;
    struct sockaddr_in serv_addr, clnt_addr;
    socklen_t clnt_addr_size;

    serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons((uint16_t)atoi(argv[1]));

    bind(serv_sock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
    listen(serv_sock, 5);
    clnt_addr_size = sizeof(clnt_addr);

    for(int i = 0;i < 3;++i) {
        op_cnt = 0;
        clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size);

        //先读第一个字符
        read(clnt_sock, &op_cnt, 1);

        recv_len = 0;
        while((op_cnt * OPSZ + 1) > recv_len) {
            recv_cnt = (int)read(clnt_sock, &opinfo[recv_len], BUF_SIZE - 1);
            recv_len += recv_cnt;
        }

        result = calculate(op_cnt, (int *)opinfo, opinfo[recv_len - 1]);
        write(clnt_sock, (char *)&result, sizeof(result));
        close(clnt_sock);
    }

    close(serv_sock);
    return 0;
}

int calculate(int opnum, int ops[], char op)
{
    int result = ops[0];
    switch(op) {
        case '+':
            for(int i = 1;i < opnum;++i) {
                result += ops[i];
            }
            break;
        case '-':
            for(int i = 1;i < opnum;++i) {
                result -= ops[i];
            }
            break;
        case '*':
            for(int i = 1;i < opnum;++i) {
                result *= ops[i];
            }
            break;
        default:
            break;
    }
    return result;
}